<template>
  <el-dialog
    v-model="visible"
    title="个人信息"
    width="500px"
    @close="handleClose"
  >
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 基本信息标签页 -->
      <el-tab-pane label="基本信息" name="profile">
        <el-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileRules"
          label-width="80px"
          style="padding: 20px"
        >
          <el-form-item label="邮箱">
            <el-input v-model="profileForm.email" disabled />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="profileForm.nickname"
              placeholder="请输入昵称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="头像">
            <div class="avatar-upload">
              <el-avatar
                :size="80"
                :src="profileForm.avatar"
                :icon="UserFilled"
              />
              <div class="avatar-upload-text">
                <el-button size="small" @click="handleAvatarUpload">
                  <el-icon><Upload /></el-icon>
                  更换头像
                </el-button>
                <p class="tip">支持 jpg、png 格式，文件小于 2MB</p>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="注册时间">
            <el-input :value="formatTime(profileForm.createTime)" disabled />
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 修改密码标签页 -->
      <el-tab-pane label="修改密码" name="password">
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="80px"
          style="padding: 20px"
        >
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入当前密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码（6-20位）"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          v-if="activeTab === 'profile'"
          type="primary"
          @click="handleUpdateProfile"
          :loading="updating"
        >
          保存信息
        </el-button>
        <el-button
          v-if="activeTab === 'password'"
          type="primary"
          @click="handleChangePassword"
          :loading="updating"
        >
          修改密码
        </el-button>
      </div>
    </template>

    <!-- 头像上传隐藏文件输入框 -->
    <input
      ref="avatarInputRef"
      type="file"
      accept="image/jpeg,image/jpg,image/png"
      style="display: none"
      @change="handleAvatarChange"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { UserFilled, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { updateUserInfo, changePassword, type UpdateUserParams, type ChangePasswordParams } from '@/api/user'

// Props 和 Emits
interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const userStore = useUserStore()

// 响应式数据
const visible = ref(false)
const activeTab = ref('profile')
const updating = ref(false)

// 表单引用
const profileFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const avatarInputRef = ref<HTMLInputElement>()

// 个人信息表单
const profileForm = reactive({
  email: '',
  nickname: '',
  avatar: '',
  createTime: ''
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules: FormRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 20, message: '昵称长度为1-20个字符', trigger: 'blur' }
  ]
}

const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 监听显示状态
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    initFormData()
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 初始化表单数据
const initFormData = () => {
  if (userStore.userInfo) {
    profileForm.email = userStore.userInfo.email
    profileForm.nickname = userStore.userInfo.nickname
    profileForm.avatar = userStore.userInfo.avatar || ''
    profileForm.createTime = userStore.userInfo.createTime
  }

  // 重置密码表单
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''

  // 重置标签页
  activeTab.value = 'profile'
}

// 格式化时间
const formatTime = (time: string): string => {
  return new Date(time).toLocaleString('zh-CN')
}

// 处理头像上传
const handleAvatarUpload = () => {
  avatarInputRef.value?.click()
}

// 处理头像文件选择
const handleAvatarChange = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (!file) return

  // 验证文件类型
  if (!['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)) {
    ElMessage.error('只支持 jpg、png 格式的图片')
    return
  }

  // 验证文件大小（2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过 2MB')
    return
  }

  // 预览头像
  const reader = new FileReader()
  reader.onload = (e) => {
    profileForm.avatar = e.target?.result as string
  }
  reader.readAsDataURL(file)

  // 清空文件输入框
  target.value = ''
}

// 更新个人信息
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return

  try {
    const valid = await profileFormRef.value.validate()
    if (!valid) return

    updating.value = true

    const params: UpdateUserParams = {
      nickname: profileForm.nickname
    }

    if (profileForm.avatar !== userStore.userInfo?.avatar) {
      params.avatar = profileForm.avatar
    }

    const updatedUser = await updateUserInfo(params)

    // 更新本地用户信息
    userStore.setUserInfo(updatedUser)

    ElMessage.success('个人信息更新成功')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '更新失败')
  } finally {
    updating.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return

    updating.value = true

    const params: ChangePasswordParams = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    }

    await changePassword(params)

    ElMessage.success('密码修改成功，请重新登录')

    // 密码修改成功后自动退出登录
    setTimeout(() => {
      userStore.logout()
    }, 1500)

    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '密码修改失败')
  } finally {
    updating.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false

  // 重置表单
  profileFormRef.value?.resetFields()
  passwordFormRef.value?.resetFields()
}
</script>

<style scoped>
.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-upload-text {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tip {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tab-pane) {
  min-height: 300px;
}
</style>